<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once('phpass-0.3/PasswordHash.php');

define('PHPASS_HASH_STRENGTH', 8);
define('PHPASS_HASH_PORTABLE', FALSE);

/**
 * SimpleLoginSecure Class
 *
 * Makes authentication simple and secure.
 *
 * Simplelogin expects the following database setup. If you are not using 
 * this setup you may need to do some tweaking.
 *   
 * 
 *   CREATE TABLE `users` (
 *     `id` int(10) unsigned NOT NULL auto_increment,
 *     `user_email` varchar(255) NOT NULL default '',
 *     `user_pass` varchar(60) NOT NULL default '',
 *     `user_date` datetime NOT NULL default '0000-00-00 00:00:00' COMMENT 'Creation date',
 *     `user_modified` datetime NOT NULL default '0000-00-00 00:00:00',
 *     `user_last_login` datetime NULL default NULL,
 *     PRIMARY KEY  (`id`),
 *     UNIQUE KEY `user_email` (`user_email`),
 *   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 * 
 * @package   SimpleLoginSecure
 * @version   2.0
 * @author    Stéphane Bourzeix, Pixelmio <stephane[at]bourzeix.com>
 * @copyright Copyright (c) 2012, Stéphane Bourzeix
 * @license   http://www.gnu.org/licenses/gpl-3.0.txt
 * @link      https://github.com/DaBourz/SimpleLoginSecure
 */
class SimpleLoginSecure
{
	protected $CI;
	protected $user_table = 'users';
	protected $isAdmin = 1;
	
	public function setUserTable($userTable) {
		$this->user_table = $userTable;
	}
	
	public function setIsAdmin($isAdmin) {
		$this->isAdmin = $isAdmin;
	}
	/**
	 * Create a user account
	 *
	 * @access	public
	 * @param	string
	 * @param	string
	 * @param	bool
	 * @return	bool
	 */
	function create($user_email = '', $user_pass = '', $auto_login = TRUE) 
	{
		$this->CI =& get_instance();
		


		//Make sure account info was sent
		if($user_email == '' OR $user_pass == '') {
			return FALSE;
		}
		
		//Check against user table
		$this->CI->db->where('user_email', $user_email); 
		$query = $this->CI->db->get_where($this->user_table);
		
		if ($query->num_rows() > 0) //user_email already exists
			return FALSE;

		//Hash user_pass using phpass
		$hasher = new PasswordHash(PHPASS_HASH_STRENGTH, PHPASS_HASH_PORTABLE);
		$user_pass_hashed = $hasher->HashPassword($user_pass);

		//Insert account into the database
		$data = array(
					'user_email' => $user_email,
					'user_pass' => $user_pass_hashed,
					'user_date' => date('c'),
					'user_modified' => date('c'),
				);

		$this->CI->db->set($data); 

		if(!$this->CI->db->insert($this->user_table)) //There was a problem! 
			return FALSE;						
				
		if($auto_login)
			$this->login($user_email, $user_pass);
		
		return TRUE;
	}

	/**
	 * Login and sets session variables
	 *
	 * @access	public
	 * @param	string
	 * @param	string
	 * @return	bool
	 */
	function login($user_email = '', $user_pass = '') 
	{
		$this->CI =& get_instance();

		if($user_email == '' OR $user_pass == '')
			return FALSE;


		//Check if already logged in
		/*if($this->CI->session->userdata('user_email') == $user_email)
			return TRUE;*/
		
		
		//Check against user table
		$this->CI->db->where('user_email', $user_email); 
		$query = $this->CI->db->get_where($this->user_table);

		$content = array();
		if ($this->CI->cart->total_items() > 0){
			foreach( $this->CI->cart->contents() as $item){
				$content[] = $item ;
			}
		}
		if ($query->num_rows() > 0) 
		{
			$user_data = $query->row_array(); 

			$hasher = new PasswordHash(8, false);

			if(!$hasher->CheckPassword($user_pass, $user_data['user_pass']))
				return FALSE;

			if ($this->CI->session->userdata('selected_country') === FALSE) {
				$selected_country = $this->CI->config->item('def_country');
			} else {
				$selected_country = $this->CI->session->userdata('selected_country');
			}
			$idAffiliate = '';
			if ($this->CI->session->userdata('selected_country') !== FALSE){
				$idAffiliate = $this->CI->session->userdata('selected_country');
			}
			
			if ($this->CI->session->userdata('selected_currency') === FALSE) {
				$selected_currency = $this->CI->config->item('def_currency');
			} else {
				$selected_currency = $this->CI->session->userdata('selected_currency');
			}
			//Destroy old session
			$this->CI->session->sess_destroy();
			
			//Create a fresh, brand new session
			$this->CI->session->sess_create();
			if (isset($user_data['discount_code'])){
				$discount = $this->CI->db->get_where('discount', array('code'=>$user_data['discount_code']))->row_array();
				if (count($discount)){
					$newdata = array(
							'discount_rate'  => $discount['percent']
					);
					$this->CI->session->set_userdata($newdata);
				}
			}
			$this->CI->db->simple_query('UPDATE ' . $this->user_table  . ' SET user_last_login = NOW() WHERE id = ' . $user_data['id']);

			//Set session data
			unset($user_data['user_pass']);
			$user_data['user'] = $user_data['user_email']; // for compatibility with Simplelogin
			$user_data['logged_in'] = TRUE;
			$user_data['admin'] = $this->isAdmin;
			$user_data['selected_currency'] = $selected_currency;
			$user_data['selected_country'] = $selected_country;
			if (!empty($idAffiliate)){
				$user_data['idAffiliate'] = $idAffiliate;
			}
			$user = array('user'=>$user_data);
			$this->CI->session->set_userdata($user_data);
			$this->CI->session->set_userdata($user);
			if(!empty($content)){
				$this->CI->cart->insert($content);
			}
			return TRUE;
		} 
		else 
		{
			return FALSE;
		}	

	}

	public function is_logged_in($admin = 0)
	{
		$this->CI =& get_instance();
		
		if ($admin != $this->CI->session->userdata('admin')) {
			return false;
		}

		if($this->CI->session->userdata('logged_in') === FALSE) 
		{
			return FALSE;
		}
		return TRUE;
	}

	/**
	 * Logout user
	 *
	 * @access	public
	 * @return	void
	 */
	function logout() {
		$this->CI =& get_instance();		

		$this->CI->session->sess_destroy();
	}

	/**
	 * Delete user
	 *
	 * @access	public
	 * @param integer
	 * @return	bool
	 */
	function delete($id) 
	{
		$this->CI =& get_instance();
		
		if(!is_numeric($id))
			return FALSE;			

		return $this->CI->db->delete($this->user_table, array('id' => $id));
	}
	
}